﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace GzucmAspBigJob.Models
{
    public class User
    {
        [Key]
        public int UserId { get; set; }

        [Required(ErrorMessage = "账号不能为空")]
        public string Account { get; set; }

        [Required(ErrorMessage = "密码不能为空")]
        public string PassWord { get; set; }

        [Required(ErrorMessage = "性别不能为空")]
        public string Gender { get; set; }

        [Required(ErrorMessage = "年龄不能为空")]
        [Range(1,120,ErrorMessage = "年龄不能超过范围")]
        public int Age { get; set; }
        
        public string PhotoUrl { get; set; }

        public override string ToString()
        {
            return "UserId=>" + UserId + " Account=>" + Account
                + " Age=>" + Age + " Gender=>" + Gender + " URL=>"+PhotoUrl;
        }
    }

    public class UserMapper
    {
        public static User QueryByUserAccount(string account)
        {
            if (account == null) return null;
            using (UserContext db = new UserContext())
            {
                var user = db.UserModels.FirstOrDefault(u => u.Account == account);
                return user;
            }
        }
        public static void UpdateUser(User user)
        {
            if (user == null) return;
            using (UserContext db = new UserContext())
            {
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
            }
        }
        public static void InsertUser(User user)
        {
            if (user == null) return;
            using (UserContext db = new UserContext())
            {
                db.UserModels.Add(user);
                db.SaveChanges();
            }
        }
    }

    public class UserContext : DbContext
    {
        public DbSet<User> UserModels { get; set; }
    }
}